<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once '/home/ali0t4/source/waya/webroot/waya_api/application/libraries/wxpay/jsapi/WxPay.JsApiPay.php';
require_once '/home/ali0t4/source/waya/webroot/waya_api/application/libraries/wxpay/jsapi/log.php';

class Treasurehunter  extends Base_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('treasurehunter_model');
        session_start();
    }
    /**
     *获取微信设备信息
     *@return array
     * */
    public function get_wx_device_params()
    {
    	$res = $this->treasurehunter_model->get_wx_device_params();
    	$this->success($res);
    }
    /**
     *获取微信设备情报
     *@param POST(uuid,major,minor)
     *@return array
     * */
    public function get_wx_device_qb()
    {
    	if(isset($_POST['uuid']) && isset($_POST['major']) && isset($_POST['minor'])){
    		$uuid = trim($_POST['uuid']);
    		$major = (int)$_POST['major'];
    		$minor = (int)$_POST['minor'];
    	}else{
    		$this->error('参数不全');
    	}
    	$res = $this->treasurehunter_model->get_wx_device_qb($uuid,$major,$minor);
    	$this->success($res);
    }
    /**
     *获取列表信息
     *@param $id
     *@return array
     * */
    public function getList()
    {
    	$res=$this->treasurehunter_model->getList();
    	$this->success($res);
    }
    /**
     *获取活动信息
     *@param $id
     *@return array 
     * */
    public function detail()
    {
    	if(isset($_GET['id']) && is_numeric($_GET['id'])){
    		$id = $_GET['id'];
    	}else{
    		$this->error('参数错误');
    	}
    	$res=$this->treasurehunter_model->detail($id);
    	$this->success($res);
    }
    
    /**
     * 判断用户是否已经报名活动
     * @param $_GET['actId'],$_GET['$issuNum']
     * @return mixed
     * */
    public function checkUserisRegistered()
    {
    	if(empty($_GET) || !isset($_GET)){
    		$this->error('GET参数不全');
    	}
    	$actId = $_GET['actId'];
    	$issueNum = $_GET['issueNum'];
    	
    	if(!isset($_SESSION)){
    		session_start();
    	} 
    	if(isset($_SESSION['uid'])){
    		$uid = $_SESSION['uid'];
    	}else{
    		$this->error('session不存在');
    	}   	
    	    	
    	$res=$this->treasurehunter_model->checkUserisRegistered($uid,$actId,$issueNum);
    	$this->success($res);
    	
    }
    /**
	 * 判断组团口令是否存在,并返回团队成员
	 * @param $_GET['actId'],$_GET['issueNum'],$_GET['grpcode']
	 * @return mixed
	 * */
    public function checkGrpcodeisExist()
    {
    	if(empty($_GET) || !isset($_GET)){
    		$this->error('GET参数不全');
    	}
    	
    	$actId=$_GET['actId'];//活动id
    	$issueNum=$_GET['issueNum'];//发团编号
    	$grpcode=$_GET['grpcode'];//组团口令
    	//用户id
    	if(!isset($_SESSION)){
    		session_start();
    	}
    	if(isset($_SESSION['uid'])){
    		$uid = $_SESSION['uid'];
    	}else{
    		$this->error('session不存在');
    	}
    	
    	$res = $this->treasurehunter_model->checkGrpcodeisExist($actId,$issueNum,$grpcode,$uid);
    	
    	if(!empty($res)){
    		$this->success($res);
    	}else{
    		$this->error("组团口令不存在");
    	}
    	
    }
    
    public function userRegister()
    {
    	if(empty($_GET) || !isset($_GET)){
    		$this->error('GET参数不全');
    	}
    	
    	$actId = $_GET['actId'];
    	$actName = $_GET['actName'];
    	$issueNum = $_GET['issueNum'];
    	$name = $_GET['name'];
    	$gender = $_GET['gender'];
    	$wxnum = $_GET['wxnum'];
    	$IdcardNum = $_GET['IdcardNum'];
    	$telNum = $_GET['telNum'];
    	$price = $_GET['price'];
    	
    	$type = $_GET['type'];
    	if($type == 'single'){
    		$inviNum = ''; 
    	}else{
    		$inviNum = $_GET['inviNum'];
    	}
    	
    	 
    	if(!isset($_SESSION)){
    		session_start();
    	}
    	if(isset($_SESSION['uid'])){
    		$uid = $_SESSION['uid'];
    	}else{
    		$this->error('session不存在');
    	}
        $data = array('uid'      => $uid,
                      'actId'    => $actId,
                      'actName'  => $actName,
        		      'issueNum' => $issueNum,
        		      'name'     => $name,
        		      'gender'   => $gender,
        		      'wxnum'    => $wxnum,
        		      'IdcardNum'=> $IdcardNum,
        		      'telNum'   => $telNum,
        		      'inviNum'  => $inviNum,
        		      'status'   => 'UNPAID',
        		      'created'  => time(),
        		      'changed'  => time(),
        		      'telCode'  => '86',
        		      'price'    => $price,
        		      'type'     => $type
        );
    	$res=$this->treasurehunter_model->userRegister($data);
    	if($res){
    		$this->success();
    	}else{
    		$this->error('系统出错，请重试');
    	}
    	 
    }
    
    
    public function pay()
    {
    	//获取活动id和发团编号
    	if(empty($_GET) || !isset($_GET)){
    		$this->error('GET参数不全');
    	}
    	 
    	$actId = $_GET['actId'];
    	$issueNum = $_GET['issueNum'];
    	
    	//获取用户openid和uid
        if(!isset($_SESSION)) session_start();
    	if(!isset($_SESSION['openid']) || !isset($_SESSION['uid'])){
    		$this->error('未登录');
    	}
    	$openid = $_SESSION['openid'];
    	$uid = $_SESSION['uid'];
    	
    	$data=$this->treasurehunter_model->registerDetail(array('uid'=>$uid,'actId'=>$actId,'issueNum'=>$issueNum));
    	if (empty($data)) {
    		echo "支付发生错误，请重试";exit();
    	}elseif ($data['status']=='PAID') {
    		echo "您已经支付过订单，无需重复支付";exit();
    	}
    	
    	//生成订单
    	$order['body'] = $data['actName'];
    	$order['out_trade_no'] = sprintf("%s%s%06d", date("Ymd"), date("Hi"), $data['id']);
    	$order['total_fee'] = $data['price'];//微信支付的金额要发送，实际价格*100
    	$order['trade_type'] = "NATIVE";
    	$order['notify_url'] = "http://api.wayatrip.com/treasurehunter/paycallback";
    	$order['product_id'] = $data['issueNum'];
    	
    	//更新报名表的out_trade_no
    	$updateres = $this->treasurehunter_model->updateRegisterDetail(array('out_trade_no'=>$order['out_trade_no']),
    			array('uid'=>$uid,'actId'=>$actId,'issueNum'=>$issueNum));
    	
    	if(!$updateres){
    		echo "支付发生错误，请重试";exit;
    	}
    	
    	$tools = new JsApiPay();
   	
    	//统一下单
    	$input = new WxPayUnifiedOrder();
    	$input->SetBody($order['body']);
    	//$input->SetAttach("test");
    	$input->SetOut_trade_no($order['out_trade_no']);
    	$input->SetTotal_fee($order['total_fee']);
    	//$input->SetTime_start(date("YmdHis"));
    	//$input->SetTime_expire(date("YmdHis", time() + 600));
    	//$input->SetGoods_tag("test");
    	$input->SetNotify_url($order['notify_url']);
    	//扫码支付
    	$input->SetTrade_type($order['trade_type']);
    	$input->SetOpenid($openid);
    	$input->SetProduct_id($order['product_id']);
    	 
    	$wxorder = WxPayApi::unifiedOrder($input);
    	//echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
    	//printf_info($order);
    	//$jsApiParameters = $tools->GetJsApiParameters($order);
    	//$this->success($order);
    	//生成二维码图片
    	$qrimg=$tools->GetQrImg($wxorder['code_url']);
    	//var_dump($qrimg);
    	$res = '<html>
    			<head>
    			  <title>'.$order['body'].'</title>
    			  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.5, minimum-scale=1, user-scalable=no">
    			</head>
    			<body style="background-color: #F2F2F2;">
                <div style="width: 160px;text-align: center;margin: 30% auto 30px;border: 1px solid #e5e5e5">
    			   <img src="'.$qrimg.'" style="width: 100%;">
    			</div>
    			<div style="text-align: center;font-size: 15px;font-weight: bold;
                line-height: 20px;">长按识别二维码，向我付款</div>
    			</body>
    			</html>';
    	echo $res;exit;
    	//$this->success($qrimg);
    	
    	//获取共享收货地址js函数参数
    	//$editAddress = $tools->GetEditAddressParameters();
    	
    	//在支持成功回调通知中处理成功之后的事宜，见 notify.php
    }
    
    public function paycallback()
    {   
    	//解码xml数据
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        
        $res = trim($postObj->result_code);
        $out_trade_no = trim($postObj->out_trade_no);
        
        $detail = $this->treasurehunter_model->registerDetail(array('out_trade_no'=>$out_trade_no));
        if (empty($detail)) {
        	 log_message('error', '微信支付通知：没有找到out_trade_no为'.$out_trade_no.'的订单');
        }
        
        //更改订单状态为已支付
        $updateres = $this->treasurehunter_model->updateRegisterDetail(array('status'=>'PAID'),
        		array('out_trade_no'=>$out_trade_no));
        if(!$updateres){
        	log_message('error', '微信支付通知：out_trade_no为'.$out_trade_no.'的订单状态更改为PAID失败');
        }
        
        //log_message('error', $postStr);
        
    	if($res=='SUCCESS'){
    		//sms参数
    		$dateStr = trim($detail['issueNum']);
    		$actDate = substr($dateStr,0,4).'-'.substr($dateStr,4,2).'-'.substr($dateStr,6,2);
    		$tpl_value = urlencode("#actName#")."=".urlencode($detail['actName'])."&".urlencode("#actDate#")."=".urlencode($actDate);
	    	$mobile = $detail['telNum'];
	    	$tpl_id = "1627806";
	    	//发送sms
	    	$this->load->library('MySms');
    		$smsres = $this->mysms->tpl_send_sms($tpl_id, $tpl_value, $mobile);
    		
    		if($smsres['code']!=0){
    			foreach($res as $k => $v){
    				log_message('error',$k.'=>'.$v);
    			}
    		} else {
    			log_message(error, "给".$smsres['mobile']."发送".$smsres['count']."条短信,模板id=".$tpl_id.",费用=".$smsres['fee']);
    		}
    		
    		echo "success";exit();
    	}else{
    		log_message('error', '微信支付通知：out_trade_no为'.$out_trade_no.'的订单支付失败,result_code:'.$res.'\n'.$postStr);
    	}
    }
    
    public function sendSms()
    {
    	$detail = $this->treasurehunter_model->registerDetail(array('id'=>$_GET['id']));
    	
    	//var_dump($detail);exit();
    	
    	//sms参数
    	$dateStr = trim($detail['issueNum']);
    	$actDate = substr($dateStr,0,4).'-'.substr($dateStr,4,2).'-'.substr($dateStr,6,2);
    	$tpl_value = urlencode("#actName#")."=".urlencode($detail['actName'])."&".urlencode("#actDate#")."=".urlencode($actDate);
    	$mobile = $detail['telNum'];
    	$tpl_id = "1627806";
    	//发送sms
    	$this->load->library('MySms');
    	$smsres = $this->mysms->tpl_send_sms($tpl_id, $tpl_value, $mobile);
    	 
    	//log_message('error', $postStr);
    }

}